package com.harmontronics.hanma.paas.paas.utils;

import org.apache.commons.lang.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ${DESCRIPTION}
 *
 * @author Five.Liu
 * @create 2017-08-30 10:18
 */
public class StringUtil extends StringUtils {

    static Pattern DOUBLE_PATTERN = Pattern.compile("^[-\\+]?[.\\d]*$");
    static Pattern CHINESE_PATTERN = Pattern.compile("[\u4E00-\u9FA5|\\！|\\，|\\。|\\（|\\）|\\《|\\》|\\“|\\”|\\？|\\：|\\；|\\【|\\】]");
    public static String regexToString(Map<String, String> putMap, String template) {
        String patternString = "\\$\\{(" + StringUtils.join(putMap.keySet(), "|") + ")\\}";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(template);
        //两个方法：appendReplacement, appendTail
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, putMap.get(matcher.group(1)));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static boolean isEmpty(Object obj) {
        if (obj instanceof List) {
            return ((List) obj).isEmpty();
        } else if (obj instanceof Set) {
            return ((Set) obj).isEmpty();
        } else if (obj instanceof Map) {
            return ((Map) obj).isEmpty();
        }
        return obj == null || obj.toString().isEmpty();
    }

    public static boolean isEmpty(String str) {
        return str == null || str.isEmpty();
    }

    public static String trim(Object str) {
        return str == null ? "" : str.toString().trim();
    }

    public static String trim(String str) {
        return str == null ? "" : str.trim();
    }

    /**
     * @return 当前时间
     */
    public static String now() {
        //  自定义格式化器
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //  获取当前日期和时间
        LocalDateTime ldt = LocalDateTime.now();
        //  第二种自定义格式化方式

        //  自定义格式化2:2017-11-04 14:30:36
        return dtf.format(ldt);
    }

    public static boolean isNumber(String number) {
        //先判断number不为空。
        if (number == null || "".equals(number)) {
            return false;
        }

        int index = number.indexOf(".");
        if (index < 0) {
            return StringUtils.isNumeric(number);
        } else {
            String num1 = number.substring(0, index);
            String num2 = number.substring(index + 1);
            return StringUtils.isNumeric(num1) && StringUtils.isNumeric(num2);
        }
    }

    /**
     * Postgresql特殊字符转义处理
     */
    public static String specialCharacterEscape(String source) {
        String result = null;
        if (StringUtils.isNotEmpty(source)) {
            result = source.replace("%", "\\%").replace("_", "\\_");
        }
        return result;
    }

    public static String getStringFromObj(Object obj) {
        return obj == null ? null : obj.toString();
    }

//    public static InnerTimeDto convertDateTime(String timeStart, String timeEnd, String date) {
//        Optional<String> prefixDateStr = Optional.ofNullable(date);
//        // 不能超过24小时
//        String today = prefixDateStr.orElse(cn.hutool.core.date.DateUtil.today());
//        if (timeStart.compareTo(timeEand) > 0) {
//            String tomorrow = cn.hutool.core.date.DateUtil.offsetDay(cn.hutool.core.date.DateUtil.parse(today, DatePattern.NORM_DATE_FORMAT), 1).toString(DatePattern.NORM_DATE_FORMAT);
//
//            Date start = cn.hutool.core.date.DateUtil.parse(StrUtil.format("{} {}", today, timeStart));
//            Date end = cn.hutool.core.date.DateUtil.parse(StrUtil.format("{} {}", tomorrow, timeEnd));
//
//            return new InnerTimeDto(start, end);
//        } else {
//            Date start = cn.hutool.core.date.DateUtil.parse(StrUtil.format("{} {}", today, timeStart));
//            Date end = cn.hutool.core.date.DateUtil.parse(StrUtil.format("{} {}", today, timeEnd));
//
//            return new InnerTimeDto(start, end);
//        }
//    }

    public static void main(String[] args) {
//        System.out.println(isNumber("0.24"));
        String content = "{{debv.sdfwe.dfwef}}135656{{sdfasdfsd.asdfwe.fsd}}";
        List<String> contentList = getI18n(content);
        for (String s : contentList) {
            System.out.println(s);
        }
    }

    /**
     * 获取表达式中${}中的值
     */
    public static List<String> getContentInfo(String content, String pattern) {
        Pattern regex = Pattern.compile(pattern);
        Matcher matcher = regex.matcher(content);
        List<String> sqlList = new ArrayList<>();
        while (matcher.find()) {
            sqlList.add(matcher.group(1));
        }
        return sqlList;
    }

    /**
     * 判断是否为浮点数，包括double和float
     *
     * @param str 传入的字符串
     * @return 是浮点数返回true, 否则返回false
     */
    public static boolean isDouble(String str) {
        if (StringUtil.isEmpty(str)) {
            return Boolean.FALSE;
        }
        return DOUBLE_PATTERN.matcher(str).matches();
    }


    /**
     * i18n国际化
     */
    public static List<String> getI18n(String content) {
        String pattern = "\\{\\{([^}]*)\\}\\}";
        return getContentInfo(content, pattern);
    }

    public static String removeFirstAndEnd(String error) {
        if (StringUtils.isNotEmpty(error)) {
            error = StringUtils.removeStart(error, "{");
            error = StringUtils.removeEnd(error, "}");
        }
        return error;
    }

    public static boolean containsChinese(String str) {

        if (StringUtils.isEmpty(str)) {
            throw new NullPointerException("str is empty!");
        }
        Matcher m = CHINESE_PATTERN.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }
}
